package zjc.bookkeeping.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;



import com.alipay.sdk.app.OpenAuthTask;
import com.mob.MobSDK;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.open.log.SLog;
import com.tencent.tauth.DefaultUiListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import zjc.bookkeeping.R;
import zjc.bookkeeping.db.AccountBean;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.db.UserBean;
import zjc.bookkeeping.model.Account;
import zjc.bookkeeping.model.User;
import zjc.bookkeeping.service.AccountService;
import zjc.bookkeeping.service.UserService;
import zjc.bookkeeping.service.imp.AccountServiceImp;
import zjc.bookkeeping.service.imp.UserServiceImp;


public class SigninActivity extends AppCompatActivity implements View.OnClickListener{

    UserBean userBean = new UserBean();
    User user;
    UserService userService = new UserServiceImp();
    AccountService accountService = new AccountServiceImp();
    boolean onlineFlag = false;

    private static final String TAG = "tencent";
    //声明Tencent实例名称
    public static Tencent mTencent;

    private static String open_id = null;
    private String qq_nickname = "";
    private String figureurl_1 = "";// 50*50的qq头像
    private int user_phone;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin);
        mTencent = Tencent.createInstance("102045986", SigninActivity.this);
        if (mTencent == null) {
            SLog.e(TAG, "腾讯实例创建失败");
            finish();
        }
        MobSDK.submitPolicyGrantResult(true);
        init();
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { 
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("request", String.valueOf(requestCode) + " " + resultCode);
        Log.d(TAG, "-->onActivityResult " + requestCode  + " resultCode=" + resultCode);
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            mTencent.onActivityResultData(requestCode,resultCode,data,loginListener);
        }
    }
    //返回接口传递的数据并跳转界面
    public void loginCallback(User resultUser) {
        Log.i("id","是："+user.getUserId());
        userBean.setUser_id(resultUser.getUserId());
        userBean.setUser_name(resultUser.getUserName());
        userBean.setUser_phone(resultUser.getUserPhone());
        userBean.setUser_qq(resultUser.getUserQq());
        userBean.setUser_zfb(resultUser.getUserZfb());
        DBManager.insertUser(userBean);
        List<Account> accountList = accountService.findAllAccount(userBean.getUser_id());
        for (int i=0; i<accountList.size(); i++){
            AccountBean accountBean = new AccountBean();
            accountBean.setAccount_name(accountList.get(i).getAccountName());
            accountBean.setAccount_time(accountList.get(i).getAccountTime());
            accountBean.setAccount_kind(accountList.get(i).getAccountType());
            accountBean.setAccount_key(accountList.get(i).getAccountUid());
            DBManager.createAccount(accountBean);
        }
        Intent intent = new Intent(SigninActivity.this, MainActivity.class);
        startActivity(intent);
    }

    //qq
    public void tencent(View v){
        Log.i("qq","登录");
        Tencent.setIsPermissionGranted(true);
        mTencent.login(this, "all", loginListener);

       // updateUserInfo();
    }

    IUiListener loginListener = new BaseUiListener() {
        @Override
        protected void doComplete(org.json.JSONObject values) {
            /** 此处回调QQ用户数据处理 */
            initOpenidAndToken(values); //初始化Token
            updateUserInfo(); //更新用户信息，头像，用户名
            //updateLoginButton(); 登录按钮更新为已登录
        }
    };

    public static void initOpenidAndToken(org.json.JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
                Log.e("openid",openId);
                open_id = openId;
            }
        } catch (Exception e) {
        }
    }

    private class BaseUiListener extends DefaultUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                //FileCodeUtil.showResultDialog(LoginActivity.this, "返回为空", "登录失败");
                Log.i("error","登录失败");
                return;
            }
//            Log.i("response", (String) response);
           // JSONObject jsonResponse = JSON.parseObject((String) response);
            org.json.JSONObject jsonResponse = (org.json.JSONObject) response;
          //  Log.i("response", (String) response);
            if (jsonResponse.length() == 0) {
                Log.i("error","登录失败");
               // FileCodeUtil.showResultDialog(LoginActivity.this, "返回为空", "登录失败");
                return;
            }
           // FileCodeUtil.showResultDialog(LoginActivity.this, response.toString(), "登录成功");
            Log.i("success","登录成功");
            doComplete((org.json.JSONObject) response);
        }

        protected void doComplete(org.json.JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
            Log.i("error",e.errorDetail);
        }

        @Override
        public void onCancel() {
            Log.i("cancel","登录取消");
        }
    }


    private void updateUserInfo() {
        Log.i("update","info");
        // 回掉成功后解析数据，Message发送数据UI线程
        if (mTencent != null && mTencent.isSessionValid()) {
            IUiListener listener = new DefaultUiListener() {
                @Override
                public void onError(UiError e) {
                }
                @Override
                public void onComplete(final Object response) {
                    Log.i("onComplete","complete");
                    Log.i("comres", String.valueOf(response));
                    String res = String.valueOf(response);
                    JSONObject jsonObject = (JSONObject) response;
                    try {
                        qq_nickname = jsonObject.getString("nickname");
                        figureurl_1 = jsonObject.getString("figureurl_qq_1");
                        Log.i("qq_nickname",qq_nickname);
                        Log.i("figureurl_1",figureurl_1);
                        user = userService.loginByQq(qq_nickname,open_id);
                        loginCallback(user);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onCancel() {

                }
            };
            UserInfo info = new UserInfo(this, mTencent.getQQToken());
            info.getUserInfo(listener);

        } else {

        }
    }
    public void back(View v){

        AlertDialog.Builder dialog = new AlertDialog.Builder(SigninActivity.this);
        dialog.setTitle("确认要退出登录嘛？");
        dialog.setIcon(R.drawable.ledger_switch);
        dialog.setNegativeButton("取消", null);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        dialog.show();

    }

    
    // 手机验证码
    EventHandler eventHandler;
    EditText editTextPhone,editTextNumber;
    Button get_code_id,login_id;
    Timer timer;
    int count = 60;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            int tag = msg.what;
            switch (tag){
                case 1:
                    int arg = msg.arg1;
                    if(arg==1){
                        get_code_id.setText("重新获取");
//计时结束停止计时把值恢复
                        count = 60;
                        timer.cancel();
                        get_code_id.setEnabled(true);
                    }else{
                        get_code_id.setText(count+"");
                    }
                    break;
                case 2:
                    Toast.makeText(SigninActivity.this,"获取短信验证码成功",Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    Log.i("Codr","获取短信验证码失败");
                    Toast.makeText(SigninActivity.this,"获取短信验证码失败",Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }

        };
    };

    private void init(){
        editTextPhone = findViewById(R.id.editTextPhone);
        editTextNumber = findViewById(R.id.editTextNumber);
        get_code_id = findViewById(R.id.get_code_id);
        get_code_id.setOnClickListener(this::onClick);
        login_id = findViewById(R.id.login_id);
        login_id.setOnClickListener(this::onClick);

        eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                Log.i("event", String.valueOf(event));
                String s = Integer.toString(result);
                Log.e("result",s);
                Log.e("data", String.valueOf(data));
                // data
                // country=86, phone=xxxxxxxxxxx
                if (result == 0){
                    Log.e("error","登录失败");
                    return;
                }
                HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
                String country = (String) phoneMap.get("country"); // 国家代码，如“86”
                String phone = (String) phoneMap.get("phone"); // 手机号码，如“13800138000”
                Log.e("data", String.valueOf(data));
// TODO 此处为子线程！不可直接处理UI线程！处理后续操作需传到主线程中操作！


//成功回调
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//提交短信、语音验证码成功
                        Log.e("result11",s);
                        user = userService.loginByPhone(phone);
                        loginCallback(user);
//                        Intent intentq = new Intent(SigninActivity.this, MainActivity.class);
//                        Bundle bundle = new Bundle(); //该类用作携带数据
//                        bundle.putInt("method",1);
//                        intentq.putExtras(bundle); //为Intent追加额外的数据
//                        startActivity(intentq);
                    }
            }
        };
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
    }

    @Override
    public void onClick(View view) {
        String phone = "";
        String code = "";
        int id = view.getId();
        switch (id){
            case R.id.get_code_id:
                phone = editTextPhone.getText().toString().trim();
                if (!TextUtils.isEmpty(phone)){
//倒计时
                    CountdownStart();
                    getVerificationCode("86",phone);
                }else{
                    Toast.makeText(this,"请输入手机号码",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.login_id:
                phone = editTextPhone.getText().toString().trim();
                code = editTextNumber.getText().toString().trim();
                if (TextUtils.isEmpty(phone)){
                    Toast.makeText(this,"请输入手机号码",Toast.LENGTH_LONG).show();
                }else if (TextUtils.isEmpty(code)){
                    Toast.makeText(this,"请输入验证码",Toast.LENGTH_LONG).show();
                }else{
//登录逻辑
                    SMSSDK.submitVerificationCode("86", phone, code);
                }
                break;
        }
    }

    /**

     * cn.smssdk.SMSSDK.class
     * 请求文本验证码
     * @param country   国家区号
     * @param phone     手机号
     */
    public static void getVerificationCode(String country, String phone){
        //获取短信验证码
        SMSSDK.getVerificationCode(country,phone);
    }

    /**cn.smssdk.SMSSDK.class

     * 请求文本验证码(带模板编号)
     * @param tempCode  模板编号
     * @param country   国家区号
     * @param phone     手机号
     */
    public static void getVerificationCode(String tempCode,String country, String phone){
        //获取短信验证码
        SMSSDK.getVerificationCode(tempCode,country,phone);
    }

    //倒计时函数
    private void CountdownStart(){
        get_code_id.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                message.arg1 = count;
                if(count!=0){
                    count--;
                }else {
                    return;
                }
                handler.sendMessage(message);
            }
        }, 1000,1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
// 使用完EventHandler需注销，否则可能出现内存泄漏
        SMSSDK.unregisterEventHandler(eventHandler);
    }


    
    // 支付宝
    public void alipay(View v){
        new Thread(){
            @Override
            public void run() {
                openAuthScheme(v);
            }
        }.start();
    }
    /**
     * 通用跳转授权业务 Demo
     */
    public void openAuthScheme(View view) {

        // 传递给支付宝应用的业务参数
        final Map<String, String> bizParams = new HashMap<>();
//		bizParams.put("url", "alipays://platformapi/startapp?appId=60000157&appClearTop=false&startMultApp=YES&sign_params=biz_content%3D%257B%2522access_params%2522%253A%257B%2522channel%2522%253A%2522ALIPAYAPP%2522%257D%252C%2522external_agreement_no%2522%253A%2522shiyun20191231_08%2522%252C%2522external_logon_id%2522%253A%2522%25E5%25A4%2596%25E9%2583%25A8%25E7%2599%25BB%25E9%2599%2586%25E5%25A5%25BD%2522%252C%2522personal_product_code%2522%253A%2522GENERAL_WITHHOLDING_P%2522%252C%2522sign_scene%2522%253A%2522INDUSTRY%257CMULTI_MEDIA%2522%257D%26sign%3DFIQnneyCyigONOb1vZnBtTF7c80pUiETOvEL4GXbQOJNyysZ0EhjPhT1dGWLgsBYw5nCtKy1nw4Bt2st89LAsq9LB9gQ2%252FiRyYwWvKkfmhIZcMTv9WF198KNOOVhK5BsHlVXA5Q99NnzF5iFdPt7N%252BDpKlraohg8papDgiudimwd1B5ByA0UMWgEJKZxzkOy4m%252F0KGc5I3TuRynp3nbzRoFzrBJuqUzEjLwlDtf1%252Brxl%252BqNBgYvYSNgctm6fyNqP%252Bm%252FDoEYl6Nr9BfAaUyxcD60dBBhKXLqaN3B1fkq7C2p9JygV3IyZDh12bUIC6pAFdbPdYEsh5fVVpEPD79xD5A%253D%253D%26timestamp%3D2020-01-08%2B18%253A08%253A57%26sign_type%3DRSA2%26charset%3DUTF-8%26app_id%3D2017090501336035%26method%3Dalipay.user.agreement.page.sign%26version%3D1.0");
        bizParams.put("url", "https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id=2021003183648526&scope=auth_base&state=init");

        // 支付宝回跳到你的应用时使用的 Intent Scheme。请设置为不和其它应用冲突的值。
        // 如果不设置，将无法使用 H5 中间页的方法(OpenAuthTask.execute() 的最后一个参数)回跳至
        // 你的应用。
        //
        // 参见 AndroidManifest 中 <AlipayResultActivity> 的 android:scheme，此两处
        // 必须设置为相同的值。
        final String scheme = "__alipaysdkdemo__";

        // 防止在支付宝 App 被强行退出等情况下，OpenAuthTask.Callback 一定时间内无法释放导致
        // Activity 泄漏。
        final WeakReference<SigninActivity> ctxRef = new WeakReference<>(this);

        // 唤起授权业务
        final OpenAuthTask task = new OpenAuthTask(this);
        task.execute(
                scheme,    // Intent Scheme
                OpenAuthTask.BizType.AccountAuth, // 业务类型
                bizParams, // 业务参数
                new OpenAuthTask.Callback() {
                    @Override
                    public void onResult(int i, String s, Bundle bundle) {
                        final Context ref = ctxRef.get();
                        if (ref != null) {
//                            showAlert(ref, String.format("结果码: %s\n结果信息: %s\n结果数据: %s", i, s, bundleToString(bundle)));
                   //         Log.e("authcode",bundle.getString("auth_code"));
                            String authCode = bundleToString(bundle);
                            Log.i("auth_Code",authCode);
                            user = userService.loginByZfb(authCode);
                            loginCallback(user);
                        }
                    }
                }, // 业务结果回调
                true); // 是否需要在用户未安装支付宝 App 时，使用 H5 中间页中转
    }


    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton(R.string.confirm, null)
                .setOnDismissListener(onDismiss)
                .show();
    }

    private static String bundleToString(Bundle bundle) {
        if (bundle == null) {
            return "null";
        }
        final StringBuilder sb = new StringBuilder();
        for (String key: bundle.keySet()) {
//            sb.append(key).append("=>").append(bundle.get(key)).append("\n");
            if(key.equals("auth_code")){
                sb.append(bundle.get(key));
                Log.i("authCode",sb.toString());
            }
        }
        return sb.toString();
    }
}